package com.song.flowable.config;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.flowable.idm.api.User;
import org.flowable.idm.engine.IdmEngineConfiguration;
import org.flowable.idm.engine.impl.UserQueryImpl;
import org.flowable.idm.engine.impl.persistence.entity.UserEntity;
import org.flowable.idm.engine.impl.persistence.entity.UserEntityImpl;
import org.flowable.idm.engine.impl.persistence.entity.UserEntityManagerImpl;
import org.flowable.idm.engine.impl.persistence.entity.data.UserDataManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.util.*;


public class CustomUserEntityManager extends UserEntityManagerImpl {

	@Autowired
	private RestTemplate restTemplate;


	public CustomUserEntityManager(IdmEngineConfiguration idmEngineConfiguration, UserDataManager userDataManager) {
		super(idmEngineConfiguration, userDataManager);
	}

	@Override
	public UserEntity findById(String entityId) {
		UserEntity userEntity = new UserEntityImpl();
		userEntity.setId("1123456");
		userEntity.setFirstName("admin");
		userEntity.setLastName("admin");
		userEntity.setDisplayName("admin");
		userEntity.setEmail("99999");
		return userEntity;
	}
	//TODO 改成redis查
	@Override
	public List<User> findUserByQueryCriteria(UserQueryImpl query) {
		String baseUrl = "http://bmp-user/flowable/getUserList";
		Map<String, Object> maps = new HashMap<>();
		maps.put("userId", query.getId());
		maps.put("groupId", query.getGroupId());
		String url = "";
		HttpHeaders headers = new HttpHeaders();
		headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
		HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
		ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
		JSONArray userList = (JSONArray) JSONObject.parseObject(response.getBody()).get("response");
		List<User> users = new ArrayList<>();
		userList.stream().forEach(user->{
			UserEntity userEntity = new UserEntityImpl();
			userEntity.setId(((JSONObject)user).getString("id"));
			userEntity.setFirstName(((JSONObject)user).getString("first"));
			userEntity.setLastName(((JSONObject)user).getString("last"));
			userEntity.setDisplayName(((JSONObject)user).getString("last"));
			userEntity.setEmail(((JSONObject)user).getString("email"));
			users.add(userEntity);
		});
		return users;
	}

	@Override
	public long findUserCountByQueryCriteria(UserQueryImpl query) {
		return 1l;
	}

}
